package com.gexiaobao.pigeon.app.network

import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.util.CacheUtil
import me.hgj.jetpackmvvm.util.LogUtils
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException


/**
 * 自定义头部参数拦截器，传入heads
 */
class MyHeadInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val token = CacheUtil.getToken()
        val language = CacheUtil.getLanguage()
        //配置请求头
        val request = chain.request()
        //从request中获取原有的HttpUrl实例oldHttpUrl
        val oldHttpUrl = request.url
        ///获取request的创建者builder
        val builder = request.newBuilder()
        //从request中获取headers，通过给定的键urlName
        val headerValues = request.headers("urlName")
        if (headerValues.isNotEmpty()) {
            //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
            builder.removeHeader("urlName")
            //匹配获得新的BaseUrl
            val headerValue = headerValues[0]

            val newBaseUrl = if (Constant.IS_LOCAL_URL) {
                getNewBaseUrl(headerValue)!!//多地址访问本地
            } else {
                Constant.SERVER_URL_FORMAL.toHttpUrlOrNull()!!//单地址访问 外网测试或正式
            }
            //重建新的HttpUrl，修改需要修改的url部分
            val newFullUrl = oldHttpUrl.newBuilder()
                .scheme(newBaseUrl.scheme) //更换网络协议
                .host(newBaseUrl.host) //更换主机名
                .port(newBaseUrl.port) //更换端口
                .build()
            /**
             * 重建这个request，通过builder.url(newFullUrl).build()
             * 然后返回一个response至此结束修改
             */
            builder.addHeader("x-token", token).build()
            builder.addHeader("language", language.ifEmpty { "zh_CN" }).build()
            LogUtils.debugInfo("x-token:$token")
            return chain.proceed(builder.url(newFullUrl).build())
        }
        return chain.proceed(builder.build())
    }

    /** 本地 */
    private fun getNewBaseUrl(headerValue: String): HttpUrl? {
        return if (url[headerValue] != null) {
            url[headerValue]!!.toHttpUrlOrNull()!!
        } else null
    }

    private val url = hashMapOf(
        Pair("url_zp", ApiService.SERVER_URL),
        Pair("url_sr", ApiService.SERVER_URL_SR),
        Pair("url_zp_shop", ApiService.SERVER_URL_ZP_SHOP),
        Pair("project", ApiService.SERVER_PROJECT_URL),
        Pair("url_im_sr", ApiService.IM_API_URL_SR),
        Pair("url_jhb", ApiService.SERVER_URL_jhb),
        Pair("url_sr_zd", ApiService.SERVER_URL_SR_ZD),
        Pair("url_sr_pm", ApiService.SERVER_URL_SR_PM),
    )
}